package servlet;

import bean.UserBean;
import dao.IUserDao;
import dao.UserDaoImp;
import service.IUserService;
import service.imp.UserServiceImp;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.time.LocalDate;
import java.util.Enumeration;

public class AddServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        UserBean user = new UserBean();
        this.fullBean(user, req);

        IUserService dao = new UserServiceImp();
        dao.add(user);
        resp.getWriter().print("注册成功！");

    }

    private void fullBean(Object beanObj, HttpServletRequest req) {
        //得到表单数据中的表单名枚举
        Enumeration<String> em = req.getParameterNames();
        //得到实体类的类模板
        Class beanClass = beanObj.getClass();

        while (em.hasMoreElements()) {//遍历枚举
            String formName = em.nextElement();//取出下一个元素
            //根据表单名，取得表单值
            String value = req.getParameter(formName);
            try {
                //根据属性名得到属性对象
                Field field = beanClass.getDeclaredField(formName);
                field.setAccessible(true);

                //给beanObj中指定的属性，赋上value值
                if (field.getType() == String.class) {
                    //给beanObj中指定的属性，赋上value值
                    field.set(beanObj, value);
                } else if (field.getType() == LocalDate.class) {
                    field.set(beanObj, LocalDate.parse(value));
                } else if (field.getType() == int.class || field.getType() == Integer.class) {
                    field.set(beanObj, Integer.parseInt(value));
                } else if (field.getType() == double.class || field.getType() == Double.class) {
                    field.set(beanObj, Double.parseDouble(value));
                }
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }

        }
    }
}
